<?php
class Identity_Manager extends Model {
	private $_is_blog_owner;
	private $_is_blog_friend;
	private $_is_community_member;
	private $_target_blogger_data;
	private $_target_blogger_id;
	private $_current_user_data;
	private $_current_user_id;
	
	function Identity_Manager() {
		parent::Model();
		$this->_is_blog_owner = FALSE;
		$this->_is_blog_friend = FALSE;
		$this->_is_community_member = FALSE;
		
		$this->_target_blogger_data = NULL;
		$this->_target_blogger_id = 0;
		$this->_current_user_data = NULL;
		$this->_current_user_id = 0;
		
		$this->load->library('auth');
		$this->load->library('common');
	}
	
	function DoIdentityCheck($_blogger_data = NULL) {
		$this->_target_blogger_data = $_blogger_data;
		if(!is_null($this->_target_blogger_data)) { // for spec. Blog
			$this->_target_blogger_id = $this->_target_blogger_data->id;
			$this->_checkIdentity();
			$this->_checkFriendPassword();
		} else { // for homepage
			$this->_checkIdentity();
		}
	}
	
	function IsBlogOwner() {
		return $this->_is_blog_owner;
	}
	
	function IsBlogFriend() {
		return $this->_is_blog_friend;
	}
	
	function IsCommunityMember() {
		return $this->_is_community_member;
	}
	
	function CurrentUserID() {
		return $this->_current_user_id;
	}
	
	function CurrentUserData() {
		return $this->_current_user_data;
	}
	
	function _checkIdentity() {
		$current_user_id = $this->common->GetSession('blogger_id'); // use session first
		if(!$current_user_id) { // no session, then cookie
			$current_user_id = $this->common->GetCookie('blogger_id');
			if(!$current_user_id) { // no cookie, then treat as guest
				return FALSE;
			}
			
			$current_pwd_hash = $this->common->GetCookie('pwd_hash');
			if(!$current_pwd_hash) { // -_-
				return FALSE;
			}
			
			if(($this->_current_user_data = $this->auth->AuthByID($current_user_id, $current_pwd_hash)) !== FALSE) { // passed!
				// set session again
				$this->common->SetSession('blogger_id', $current_user_id);
				$this->common->SetSession('blogger_data', json_encode($this->_current_user_data));
				$this->_setIdentity($current_user_id);
			} else {
				return FALSE;
			}
		} else { // session exists
			$this->_current_user_data = json_decode($this->common->GetSession('blogger_data'));
			$this->_setIdentity($current_user_id);
		}
	}
	
	function _setIdentity($cruid) {
		$this->_current_user_id = $cruid;
		$this->_is_community_member = TRUE; // of course!
		
		if($cruid == $this->_target_blogger_id) {
			$this->_is_blog_friend = TRUE; // of course!
			$this->_is_blog_owner = TRUE; // even...
		}
	}
	
	function _checkFriendPassword() {
		// ...
		$cookie_key = 'friend_pwd_hash';
		$fph = $this->common->GetCookie($cookie_key);
		if($fph === FALSE) { // no cookie, then not friend
			return FALSE;
		}
		foreach($fph as $n => $v) {
			if($n == $this->_target_blogger_id) {
				if(strcmp(md5($this->_target_blogger_data->friend_password), $v) == 0) {
					$this->_is_blog_friend = TRUE;
					return;
				}
			}
		}
	}
}
?>